/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.variable;

import tal.drivechain.variable.types.DataType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import tal.drivechain.chain.script.ScriptGenerator;

/**
 *
 * @author Main
 */
public class VarTable extends HashMap<String,Variable> implements ScriptGenerator {
    private List<VarTableListener> listeners = new ArrayList<VarTableListener>();
    private List<String> publicVars = new ArrayList<String>();

    public void addListener(VarTableListener listener) {
        listeners.add(listener);
    }

    public void removeListener(VarTableListener listener) {
        listeners.remove(listener);
    }

    public void setPublicVar(String varName, boolean publicVar) {
//        System.out.println("setPublicVar");
        if (!this.containsKey(varName))
            throw new IllegalArgumentException("Variable " + varName + " does not exist in var table.");
        Variable v = get(varName);
        if (publicVar) {
            if (!publicVars.contains(v.getName())) {
//                System.out.println("varScopeChanged true");
                publicVars.add(v.getName());
                for (VarTableListener l : listeners.toArray(new VarTableListener[0])) l.varScopeChanged(v, true);
            }
        } else {
            if (publicVars.contains(v.getName())) {
//                System.out.println("varScopeChanged false");
                publicVars.remove(v.getName());
                for (VarTableListener l : listeners.toArray(new VarTableListener[0])) l.varScopeChanged(v, false);
            }
        }
    }

    public boolean isPublicVar(String varName) {
        if (!this.containsKey(varName))
            throw new IllegalArgumentException("Variable " + varName + " does not exist in var table.");

        return publicVars.contains(varName);
    }

    public void sendGlobalMessage(Variable message) {
        for (VarTableListener l : listeners) l.globalMessageEvent(message);
    }    
    
    public void sendSetVarMessage(Variable message) {
        for (VarTableListener l : listeners) l.setVarEvent(message);
    }

    @Override
    public Variable remove(Object o) {
        Variable v = super.remove(o);
        for (VarTableListener l : listeners) l.removeVarEvent(v);
        return v;
    }

    public static boolean isValidVarName(String varname) {
        // TODO work on isValidVarName in VarTable.
        varname = varname.toLowerCase().trim();
        if (varname.startsWith("sys.") || varname.startsWith("~") || !varname.matches("[a-zA-Z][a-zA-Z0-9$]*")
            || varname.indexOf('[')!=-1 || varname.indexOf('#')!=-1 || varname.indexOf(']')!=-1 ||
                    varname.indexOf('_')!=-1 || varname.equals("expr") || varname.equals("int"))
            return false;
        try {
            DataType.parseType(varname);
            return false;
        } catch (IllegalArgumentException ie) {
            return true;
        }
    }

    public String generateScript() {
        String script = "";
        for (String name : this.keySet()) {
            try {
                Variable v = this.get(name);
                if (isPublicVar(name))
                    script += "public ";
                script += "variable " + v.generateScript() + ";\n";
            } catch (IllegalArgumentException ie) {
                throw new IllegalArgumentException("In variable " + name + ": " + ie.getMessage());
            }
        }
        return script;
    }

    @Override
    public synchronized void clear() {
        super.clear();
        publicVars.clear();
        // TODO: The listener list must be cleared as well at some point if we want to delete the object completely
    }
}
